//
//
//
//		宗申通机
//		
//
//app.js
App({

    onLaunch: function () {
        // 展示本地存储能力
        // var logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)
        //this.usrserviceuuid = wx.getStorageSync('usrserviceuuid') || "0000FFE0-0000-1000-8000-00805F9B34FB"

        wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/background_image/1/',
            success: (restem) => {
                console.log(restem)
                // this.setData({
                //   helloImgUrl : restem.data.background_image
                // })
            }
        })

        this.globalData.phoneSystem = "android"

        setInterval(this.getBindBlueInfo, 1000*60) // 每分钟查询绑定蓝牙
        
        wx.getSystemInfo({
            success: (res) => {
                if (res.platform == "devtools") {
                    this.globalData.phoneSystem = "PC"
                } else if (res.platform == "ios") {
                    this.globalData.phoneSystem = "ios"
                } else if (res.platform == "android") {
                    this.globalData.phoneSystem = "android"
                }
            }
        })
    }, readUUID: function () {
        this.globalData.usrserviceuuid = wx.getStorageSync('usrserviceuuid') || "0000FFE0-0000-1000-8000-00805F9B34FB"
        this.globalData.usrrxduuid = wx.getStorageSync('usrrxduuid') || "0000FFE1-0000-1000-8000-00805F9B34FB"
        this.globalData.usrtxduuid = wx.getStorageSync('usrtxduuid') || "0000FFE1-0000-1000-8000-00805F9B34FB"
        this.globalData.muuidSel = wx.getStorageSync('lastsel') || 0
        console.log(this.globalData.usrrxduuid)
        console.log("Read = ", this.globalData.usrserviceuuid, this.globalData.usrtxduuid, this.globalData.usrrxduuid)
    }, readSetting: function () {
        this.readUUID()
        this.globalData.mautoSendInv = wx.getStorageSync('autoSendInv') || 100
        this.globalData.msendText = wx.getStorageSync('sendText') || "1024"
        this.globalData.muuidSel = wx.getStorageSync('lastsel') || 0
        switch (this.globalData.muuidSel) {
            case 0:
                this.globalData.mserviceuuid = "0000FFE0-0000-1000-8000-00805F9B34FB"
                this.globalData.mtxduuid = "0000FFE1-0000-1000-8000-00805F9B34FB"
                this.globalData.mrxduuid = "0000FFE1-0000-1000-8000-00805F9B34FB"
                break;
            case 1:
                this.globalData.mserviceuuid = "0000FFE0-0000-1000-8000-00805F9B34FB"
                this.globalData.mtxduuid = "0000FFE2-0000-1000-8000-00805F9B34FB"
                this.globalData.mrxduuid = "0000FFE1-0000-1000-8000-00805F9B34FB"
                break;
            case 2:
                this.globalData.mserviceuuid = this.globalData.usrserviceuuid
                this.globalData.mtxduuid = this.globalData.usrtxduuid
                this.globalData.mrxduuid = this.globalData.usrrxduuid
                break;
        }
        console.log("readSetting ", this.globalData.mautoSendInv, this.globalData.msendText)
    }, saveSetting(time, text) {
        wx.setStorageSync('autoSendInv', time)
        wx.setStorageSync('sendText', text)
        console.log("WriteSetting ", time, text)
    }, savelastsel(sel) {
        wx.setStorageSync('lastsel', sel)
        console.log("Writelastsel ", sel)
    }, saveusrUUID: function (id_s, id_t, id_r) {
        this.globalData.usrserviceuuid = id_s
        this.globalData.usrrxduuid = id_r
        this.globalData.usrtxduuid = id_t
        wx.setStorageSync('usrserviceuuid', id_s)
        wx.setStorageSync('usrrxduuid', id_r)
        wx.setStorageSync('usrtxduuid', id_t)
        console.log("Save usr = ", id_s, id_t, id_r)
    },
    // 获取绑定蓝牙信息
    getBindBlueInfo() {
        // https://cqygdqkj.top/
        this.globalData.bindedInfo = {}
        wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/user_bind_info/',
            method: "GET",
            header: {
                "Authorization": this.globalData.headerToken,
            },
            success: (res) => {
                console.log("获取蓝牙绑定信息成功", res)
                console.log(res.data.data.page_count)
                for(var i = 0; i < res.data.data.page_count; i++){
                    this.getBindBlueInfoByPage(i+1);
                }
            },
            fail: (res) => {
                console.log(res)
            },
        })
    },
    getBindBlueInfoByPage(page){
        var parm = "?page="
        parm = parm + page
        wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/user_bind_info/' + parm,
            method: "GET",
            header: {
                "Authorization": this.globalData.headerToken,
            },
            success: (res) => {
                console.log("查询页: ", page)
                for(var j = 0; j < res.data.data.list.length; j ++) {
                    this.globalData.bindedInfo[res.data.data.list[j].id] = res.data.data.list[j]
                }
            },
            fail: (res) => {
                console.log(res)
            },
        })
    },
    checkIsBindedByNameOfInfo(name){
        // 0: 未绑定 1：已被其他用户绑定 2：绑定的用户是自己
        var arrays = Object.values(this.globalData.bindedInfo)
        for(var i = 0; i < arrays.length; i++){
            if(arrays[i].machine_info == name){
                console.log("检查绑定情况：", arrays[i])
                if(arrays[i].is_save == false)
                    return 0
                if(arrays[i].user == this.globalData.userId)
                    return 2
                // if(arrays[i].is_checked == true)
                //     return 2
                return 1
            }
        }
        return 0
    },
    getBindedUserById(id){
        return this.globalData.bindedInfo[id].user
    },
    // 获取用户id
    getUserId(){
        // https://cqygdqkj.top/api/v1/zqwb/user_id/
        wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/user_id/',
            method: "GET",
            header: {
                "Authorization": this.globalData.headerToken,
            },
            success: (res) => {
                console.log("获取用户id成功", res, res.data.data.id)
                this.globalData.userId = res.data.data.id;
            },
            fail: (res) => {
                console.log("获取用户id失败", res)
            },
        })
        
    },
    // 获取参数说明表
    getCmdDescTable() {
        if (this.globalData.CmdDescTable == null) {
            wx.request({ // /api/v1/zqwb/app_desc/?page=2
                url: 'https://cqygdqkj.top' + '/api/v1/zqwb/app_desc/all/',
                method: "GET",
                success: (restem) => {
                    console.log("获取参数描述信息成功")
                    this.globalData.CmdDescTable = restem.data.data
                    console.log(this.globalData.CmdDescTable)
                },
                fail: (res) => {
                    wx.showToast({
                        title: res.errMsg,
                    })
                },
            })
        }
        return this.globalData.CmdDescTable
    },
    // 获取更新固件的信息
    getUpdateInfo() {
        this.globalData.updateFileUrl = ""
        wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/update_info/1/',
            method: "GET",
            header: {
                "Authorization": this.globalData.headerToken
            },
            success: (res) => {
                console.log("获取更新信息成功")
                console.log(res.data.data.soft_file)
                this.globalData.updateFileUrl = res.data.data.soft_file
                this.downUpdateFile()
            }
        })
    },
    // 下载固件
    downUpdateFile() {
        this.globalData.updateFilePath = ""
        wx.downloadFile({
            url: this.globalData.updateFileUrl,
            success: (res) => {
                if (res.statusCode === 200) {
                    console.log("缓存下载固件包成功")
                    console.log(res.tempFilePath)
                    this.globalData.updateFilePath = res.tempFilePath
                }
            }
        })
    },
    globalData: {
        mserviceuuid: "0000FFE0-0000-1000-8000-00805F9B34FB",
        mtxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",
        mrxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",
        /*
        mserviceuuid: "0000FFE0-0000-1000-8000-00805F9B34FB", //hc08
        mtxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",
        mrxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",*/
        usrserviceuuid: "0000FFE0-0000-1000-8000-00805F9B34FB",
        usrtxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",
        usrrxduuid: "0000FFE1-0000-1000-8000-00805F9B34FB",
        muuidSel: 0,
        mautoSendInv: 10,
        msendText: "",
        ble_device: null,

        //蓝牙二维码信息
        bluetoothName: "",
        bluetoothMac: "",

        // 登录HeaderToken;
        headerToken: "",
        userId: null,
        // 蓝牙绑定信息
        bindedInfo: {}, // {id , blueName}

        //正在连接的蓝牙设备信息
        deviceId: "",
        serviceId: "",
        characteristicId: "",
        connected: false,
        isDataChanged: false,
        isUpdateting: false, //正在更新
        isReStartUpdate: false, //在主页监听到正在更新
        restartUpdateVertion: "", //版本
        CmdDescTable: null, // 参数表
        //系统
        phoneSystem: "",

        //当前读取的下位机固件版本
        newVersion: "V000",

        //固件更新路径
        updateFileUrl: "",
        updateFilePath: ""
    },
    data:{
        testName : "BT24",
    }

})

// 创建缓存管理器
const cacheManager = wx.createCacheManager({
    origin: 'https://cqygdqkj.top/',
})

// 添加请求规则
cacheManager.addRules([
    '/api/v1/zqwb/blue_info/',
    '/api/v1/zqwb/background_image/1/',
    '/api/v1/zqwb/instruct_info/',
    '/api/v1/user/wechat_login/',
])

// 监听符合规则的 wx.request 请求，默认在弱网时调用 wx.request 即会触发
cacheManager.on('request', evt => {
    return new Promise((resolve, reject) => {
        // 匹配是否存在缓存
        const matchRes = cacheManager.match(evt)

        if (matchRes && matchRes.data) {
            // 使用缓存返回
            resolve(matchRes.data)
        } else {
            // 没有匹配到缓存
            reject({ errMsg: `catch not found: ${evt.url}` })
        }
    })
})
